<template>
  <div style="height: 100%">
    <g-dynamic-table
      type="notifications"
      ref="table"
      :fetch="fetchDataList"
      @action-click="handleActionClick"
      :showExport="true"
    >
      <template #headerCell="{ column }">
        <template v-if="column.field == 'No'">
          {{ column.title }}
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'displayName'">
          <span>{{ record.displayName }}</span>
          <a-tag v-if="record.isStatic" color="#108ee9"> {{ l('Static') }}</a-tag>
          <a-tag v-if="record.isDefault" color="#2db7f5"> {{ l('Default') }}</a-tag>
        </template>
      </template>
    </g-dynamic-table></div
  >
</template>
<script lang="ts">
  import {
    GetUserNotificationsInput,
    NotificationServiceProxy,
    UserNotification,
  } from '/@/shared/service-proxies/service-proxies';
  import userNotificationHelper, {
    IFormattedUserNotification,
  } from '/@/shared/helpers/UserNotificationHelper';
  import { AppComponentBase } from '/@/shared/component-base';
  import { defineComponent } from 'vue';
  import GDynamicTable from '/@/shared/components/g-dynamic-table/index.vue';
  import { EVENT_BTN_ENUM } from '/@/shared/components/g-dynamic-table/enums/event-btn-enum';

  export default defineComponent({
    name: 'notifications-news',
    components: {
      GDynamicTable,
    },
    mixins: [AppComponentBase],
    data() {
      return {
        dataList: [] as UserNotification[],
        notificationService: new NotificationServiceProxy(),
        userNotificationHelper: userNotificationHelper,
        fetchinput: new GetUserNotificationsInput(),
      };
    },
    created() {
      this.notificationService = new NotificationServiceProxy(this.$apiUrl, this.$api);
      this.userNotificationHelper.init();
    },
    methods: {
      /**
       * 获取数据
       */
      fetchDataList(otherQuery) {
        const { maxResultCount, skipCount, state, StartTime, EndTime } = (
          this.$refs.table as any
        ).getSearchProps();
        this.fetchinput.startTime = StartTime;
        this.fetchinput.endTime = EndTime;
        this.fetchinput.state = state;
        this.fetchinput.maxResultCount = !!otherQuery ? otherQuery.maxResultCount : maxResultCount;
        this.fetchinput.skipCount = !!otherQuery ? otherQuery.skipCount : skipCount;
        return new Promise((resolve, reject) => {
          this.notificationService
            .getPagedUserNotifications(this.fetchinput)
            .finally(() => {
              // finishedCallback!();
            })
            .then((res) => {
              this.dataList = this.formatNotifications(res.items as UserNotification[]).map(
                (item) => item.formattedNotification,
              );
              resolve(this.dataList);
            })
            .catch((error) => {
              reject(error);
            });
        });
      },
      /** 单条消息设置已读 */
      setAsRead(item: IFormattedUserNotification) {
        this.userNotificationHelper.setAsRead(item.userNotificationId, () => {});
      },
      /** 删除消息 */
      deleteItem(item: IFormattedUserNotification) {
        this.notificationService.deleteNotification(item.userNotificationId).then(() => {
          this.notify.success(this.l('SuccessfullyDeleted'));
        });
      },
      /** 全部设为已读 */
      setAllUserNotificationsAsRead() {
        this.userNotificationHelper.setAllAsRead();
      },
      /** 格式化消息 */
      formatNotifications(records: any[]): any[] {
        const formattedRecords = [];
        for (const record of records) {
          record.formattedNotification = this.formatRecord(record);
          formattedRecords.push(record as never);
        }
        return formattedRecords;
      },
      formatRecord(record: any): IFormattedUserNotification {
        return this.userNotificationHelper.format(record, false);
      },

      /**
       * 按钮回调事件
       */
      handleActionClick(event: string, item?: any) {
        console.log(event);
        switch (event) {
          case EVENT_BTN_ENUM.CREATE:
            this.setAllUserNotificationsAsRead();
            break;
          case EVENT_BTN_ENUM.DELETE:
            this.deleteItem(item);
            break;
          case EVENT_BTN_ENUM.EDIT:
            this.setAsRead(item);
            break;
          default:
            break;
        }
      },
    },
  });
</script>
